<script lang="jsx" setup>
import { ref } from 'vue';
import { printQrCode } from '@/service/api/modules/trace/print-qr-code';
import QrCodeList from './qr-code-list.vue';

const props = defineProps({
  type: {
    type: String,
    default: () => null
  }
});

const visible = defineModel('visible', { type: Boolean, default: false });
const loading = ref(false);
const qrCodeListRef = ref(null);

function doPrint(val) {
  const ordonnance = document.getElementById(val).contentWindow;
  let timer = setTimeout(() => {
    ordonnance.print();
    clearTimeout(timer);
    timer = null;
    loading.value = false;
  }, 500);
}
function handlePrint() {
  qrCodeListRef.value.handlePrint(params => {
    loading.value = true;
    printQrCode(params).then(({ data, error }) => {
      console.log(data);

      const boldData = new Blob([data], { type: 'application/pdf' });
      const oldIframe = document.getElementById('printPdf');
      if (oldIframe) {
        oldIframe.parentNode.removeChild(oldIframe);
      }
      const iframe = document.createElement('iframe');
      iframe.style.frameborder = 'none';
      iframe.style.display = 'none';
      iframe.style.pageBreakBefore = 'always';
      iframe.setAttribute('id', 'printPdf');
      iframe.setAttribute('name', 'printPdf');
      iframe.src = window.URL.createObjectURL(boldData);
      document.body.appendChild(iframe);
      doPrint('printPdf');
      window.URL.revokeObjectURL(iframe.src);
    });
  });
}
</script>

<template>
  <Modal v-model:visible="visible" title="二维码" height="70vh" width="1000px" :destroy-on-close="true">
    <QrCodeList ref="qrCodeListRef" :type="props.type" />
    <template #footer>
      <div class="modal-footer">
        <AButton @click="visible = false">关闭</AButton>
        <AButton type="primary" :loading="loading" @click="handlePrint">打印</AButton>
      </div>
    </template>
  </Modal>
</template>

<style lang="scss" scoped></style>
